package com.zhiyume.api.controller;

import com.zhiyume.api.util.ApiClassifyEnum;
import com.zhiyume.api.util.ApiConstants;
import com.zhiyume.api.util.ApiFloorEnum;
import com.zhiyume.api.util.ApiOperateEnum;
import com.zhiyume.controller.BaseController;
import com.zhiyume.dao.api.TInformationMapper;
import com.zhiyume.dao.api.TInformationSelfMapper;
import com.zhiyume.dao.entity.TInformation;
import com.zhiyume.dao.entity.TInformationCriteria;
import com.zhiyume.page.PageReq;
import com.zhiyume.page.Pager;
import com.zhiyume.service.InformationService;
import com.zhiyume.service.common.ConstantEnum;
import com.zhiyume.service.util.DateUtil;
import com.zhiyume.service.util.JsonUtil;
import com.zhiyume.service.util.StringUtil;
import com.zhiyume.util.TypeConstants;
import com.zhiyume.vo.NavReqVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wang on 17/10/20.
 */
@RestController
@RequestMapping("/api/home")
@Api(tags = "APP首页及官网数据获取来源")
public class HomePageAction extends BaseController{

    private static final Logger logger = LoggerFactory.getLogger(HomePageAction.class);

    @Autowired
    private InformationService informationService;

    @Autowired
    TInformationMapper tInformationMapper;
    @Autowired
    TInformationSelfMapper tInformationSelfMapper;

    private String successType = ConstantEnum.CONSTANT_SUCCESS.getErrType();
    private String successMsg = ConstantEnum.CONSTANT_SUCCESS.getErrMsg();

    private int STATUS_PUBLISHED = Integer.parseInt((String)TypeConstants.statusMap.get(TypeConstants.STATUS_PUBLISHED));
    private String SLIDER_FLOOR = (String)TypeConstants.floorMap.get(TypeConstants.SLIDER_FLOOR);


    /**
     * 首页轮播
     */
    @RequestMapping(value = "/recommend/slider", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查询热搜轮播")
    @ResponseBody
    public Map queryRecommendSlider(PageReq page) throws Exception{
        Pager p = getRecommendShowPager(page);
        return JsonUtil.returnResult(successType, successMsg,p);
    }

    /**
     * 首页数据
     */
    @RequestMapping(value = "/recommend/list", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查询热搜列表")
    @ResponseBody
    public Map queryRecommendDatas(PageReq page) throws Exception{
        Pager p = getRecommendDataPager(page);
        return JsonUtil.returnResult(successType, successMsg,p);
    }


    /**
     * 电影轮播
     */
    @RequestMapping(value = "/movie/slider", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查询电影轮播")
    @ResponseBody
    public Map queryMovieSlider(PageReq page) throws Exception{
        Pager p = getClassifyShowPager(ApiClassifyEnum.MOVIE.getIndex(),page);
        return JsonUtil.returnResult(successType, successMsg,p);

    }

    /**
     * 电影数据
     */
    @RequestMapping(value = "/movie/list", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查询电影列表")
    @ResponseBody
    public Map queryMovieDatas(PageReq page) throws Exception{
        Pager p = getClassifyDataPager(ApiClassifyEnum.MOVIE.getIndex(),page);
        return JsonUtil.returnResult(successType, successMsg,p);

    }


    /**
     * 电视轮播
     *
     */
    @RequestMapping(value = "/tel/slider", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查询电视轮播")
    @ResponseBody
    public Map queryTelSlider(PageReq page) throws Exception{
        Pager p = getClassifyShowPager(ApiClassifyEnum.TEL.getIndex(),page);
        return JsonUtil.returnResult(successType, successMsg,p);

    }

    /**
     * 电视数据
     *
     */
    @RequestMapping(value = "/tel/list", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查询电视列表")
    @ResponseBody
    public Map queryTelDatas(PageReq page) throws Exception{
        Pager p = getClassifyDataPager(ApiClassifyEnum.TEL.getIndex(),page);
        return JsonUtil.returnResult(successType, successMsg,p);

    }


    /**
     * 网剧轮播
     */
    @RequestMapping(value = "/net/slider", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查询网剧轮播")
    @ResponseBody
    public Map queryNetworkSlider(PageReq page) throws Exception{
        Pager p = getClassifyShowPager(ApiClassifyEnum.NET.getIndex(),page);
        return JsonUtil.returnResult(successType, successMsg,p);
    }

    /**
     * 网剧数据
     */
    @RequestMapping(value = "/net/list", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查询网剧列表")
    @ResponseBody
    public Map queryNetworkDatas(PageReq page) throws Exception{
        Pager p = getClassifyDataPager(ApiClassifyEnum.NET.getIndex(),page);
        return JsonUtil.returnResult(successType, successMsg,p);
    }


    /**
     * 明星轮播
     */
    @RequestMapping(value = "/actor/slider", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查询明星轮播")
    @ResponseBody
    public Map queryActorSlider(PageReq page) throws Exception{
        Pager p = getClassifyShowPager(ApiClassifyEnum.ACTOR.getIndex(),page);
        return JsonUtil.returnResult(successType, successMsg,p);
    }

    /**
     * 明星数据
     */
    @RequestMapping(value = "/actor/list", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查询明星列表")
    @ResponseBody
    public Map queryActorDatas(PageReq page) throws Exception{
        Pager p = getClassifyDataPager(ApiClassifyEnum.ACTOR.getIndex(),page);
        return JsonUtil.returnResult(successType, successMsg,p);
    }

    /**
     * 综艺数据
     */
    @RequestMapping(value = "/variety/list", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查询综艺列表")
    @ResponseBody
    public Map queryVarietyDatas(PageReq page) throws Exception{
        Pager p = getClassifyDataPager(ApiClassifyEnum.VARIETY.getIndex(),page);
        return JsonUtil.returnResult(successType, successMsg,p);
    }

    /**
     * 综艺轮播
     */
    @RequestMapping(value = "variety/slider", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查询综艺轮播")
    @ResponseBody
    public Map queryVarietySlider(PageReq page) throws Exception{
        Pager p = getClassifyShowPager(ApiClassifyEnum.VARIETY.getIndex(),page);
        return JsonUtil.returnResult(successType, successMsg,p);
    }

    /**
     * 时尚轮播
     */
    @RequestMapping(value = "fashion/slider", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查询时尚轮播")
    @ResponseBody
    public Map queryFashionSlider(PageReq page) throws Exception{
        Pager p = getClassifyShowPager(ApiClassifyEnum.FASHION.getIndex(),page);
        return JsonUtil.returnResult(successType, successMsg,p);
    }

    /**
     * 时尚数据
     */
    @RequestMapping(value = "fashion/list", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查询时尚列表")
    @ResponseBody
    public Map queryFashionDatas(PageReq page) throws Exception{
        Pager p = getClassifyDataPager(ApiClassifyEnum.FASHION.getIndex(),page);
        return JsonUtil.returnResult(successType, successMsg,p);
    }

    /**
     * 音乐轮播
     */
    @RequestMapping(value = "music/slider", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查询音乐轮播")
    @ResponseBody
    public Map queryMusicSlider(PageReq page) throws Exception{
        Pager p = getClassifyShowPager(ApiClassifyEnum.MUSIC.getIndex(),page);
        return JsonUtil.returnResult(successType, successMsg,p);
    }

    /**
     * 音乐数据
     */
    @RequestMapping(value = "music/list", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查询音乐列表")
    @ResponseBody
    public Map queryMusicDatas(PageReq page) throws Exception{
        Pager p = getClassifyDataPager(ApiClassifyEnum.MUSIC.getIndex(),page);
        return JsonUtil.returnResult(successType, successMsg,p);
    }

    /**
     * 首页数据
     */
    @RequestMapping(value = "nav/list", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "搜索列表")
    @ResponseBody
    public Map queryNavDatas(NavReqVO page) throws Exception{
        Pager p = getNavDataPager(page);
        return JsonUtil.returnResult(successType, successMsg,p);
    }

    //推荐轮播数据
    private Pager getRecommendShowPager(PageReq page) throws Exception{
        Pager p = new Pager();

        if(page.getPageSize()>ApiConstants.MAX_NUM)
            throw new Exception("pageSize超负荷");


        TInformationCriteria t = new TInformationCriteria();
        TInformationCriteria.Criteria ct = t.createCriteria();
        ct.andFloorTypeEqualTo(ApiFloorEnum.SLIDER.getValue()).
                andStatusEqualTo(STATUS_PUBLISHED).
                andIsIntroEqualTo(0);

        //上下架
        ct.andIsShowEqualTo(TypeConstants.AppConstants.IF_INFO_SHOW);
        //翻页
        t.setLimitStart(0);
        t.setLimitEnd(ApiConstants.SLIDER_PAGE);

        informationService.orderByAndSetId(page, t, ct);

        p.setTotalCount(tInformationMapper.countByExample(t));

        List<TInformation> ts = tInformationMapper.selectByExample(t);
        List datas = getSliderRenderData(ts);

        p.setPageSize(page.getPageSize());

        p.setItems(datas);
        return p;
    }

    //需要获取阿里云的配置
    private boolean ifAliyunImg(TInformation art){
        return StringUtil.isBlank(art.getCoverUrl1()) ||
                (Integer.parseInt(TypeConstants.floorMap.get(TypeConstants.IMAGE_BIG_FLOOR))==art.getImgStatus());
    }

    //普通栏目轮播数据
    private Pager getClassifyShowPager(int classify,PageReq page) throws Exception{
        Pager p = new Pager();

        if(page.getPageSize()>ApiConstants.MAX_NUM)
            throw new Exception("pageSize超负荷");

        int id = getTemplateId(classify);

        TInformationCriteria t = new TInformationCriteria();
        TInformationCriteria.Criteria ct = t.createCriteria();
        ct.andNavTypeEqualTo(id).
                andStatusEqualTo(STATUS_PUBLISHED).
                andFloorTypeEqualTo(SLIDER_FLOOR).
                andIsIntroNotEqualTo(0);

        //上下架
        ct.andIsShowEqualTo(TypeConstants.AppConstants.IF_INFO_SHOW);
        //翻页
        t.setLimitStart(0);
        t.setLimitEnd(ApiConstants.SLIDER_PAGE);

        informationService.orderByAndSetId(page, t, ct);

        p.setTotalCount(tInformationMapper.countByExample(t));

        List<TInformation> ts = tInformationMapper.selectByExample(t);

        List datas = getSliderRenderData(ts);

        p.setPageSize(page.getPageSize());

        p.setItems(datas);

        logger.info(p.toString());

        return p;
    }

    //获取模板id
    private int getTemplateId(int classify) {
        return classify;
    }

    //推荐列表数据获取
    private Pager getRecommendDataPager(PageReq page) throws Exception{
        Pager p = new Pager();

        if(page.getPageSize()>ApiConstants.MAX_NUM)
            throw new Exception("pageSize超负荷");


        TInformationCriteria t = new TInformationCriteria();
        TInformationCriteria.Criteria ct = t.createCriteria();
        //速度会有些慢
        List<String> codes = new ArrayList<>();
        codes.add(ApiFloorEnum.SLIDER.getValue());
        codes.add(ApiFloorEnum.TOP.getValue());
        ct.andFloorTypeNotIn(codes).andStatusEqualTo(STATUS_PUBLISHED).
                andIsIntroEqualTo(TypeConstants.AppConstants.IF_INTRO);

        //上下架
        ct.andIsShowEqualTo(TypeConstants.AppConstants.IF_INFO_SHOW);

        //翻页
        t.setLimitStart(0);
        t.setLimitEnd(page.getPageSize());

        informationService.orderByAndSetId(page, t, ct);

        p.setTotalCount(tInformationMapper.countByExample(t));


        List<TInformation> ts = tInformationMapper.selectByExample(t);
        List<Map> datas = new ArrayList<Map>();

        if(ApiOperateEnum.REFRESH.getName().equals(page.getHandle())){
            List<Map> top = getRecommendTopData();
            if(CollectionUtils.isNotEmpty(top)){
                datas.addAll(top);
            }
        }

        datas.addAll(getRenderData(ts));

        p.setPageSize(page.getPageSize());

        p.setItems(datas);

        logger.info(p.toString());
        return p;
    }

    //普通栏目列表数据获取
    private Pager getClassifyDataPager(int classify,PageReq page) throws Exception{
        Pager p = new Pager();

        if(page.getPageSize()>ApiConstants.MAX_NUM)
            throw new Exception("pageSize超负荷");

        int id = getTemplateId(classify);

        TInformationCriteria t = new TInformationCriteria();
        TInformationCriteria.Criteria ct = t.createCriteria();
        //速度会有些慢
        List<String> codes = new ArrayList<>();
        codes.add(ApiFloorEnum.SLIDER.getValue());
        codes.add(ApiFloorEnum.TOP.getValue());
        ct.andNavTypeEqualTo(id).
                andFloorTypeNotIn(codes).
                andStatusEqualTo(STATUS_PUBLISHED).
                andIsIntroNotEqualTo(TypeConstants.AppConstants.IF_INTRO);
        //上下架
        ct.andIsShowEqualTo(TypeConstants.AppConstants.IF_INFO_SHOW);

        //翻页
        t.setLimitStart(0);
        t.setLimitEnd(page.getPageSize());

        informationService.orderByAndSetId(page, t, ct);

        p.setTotalCount(tInformationMapper.countByExample(t));


        List<TInformation> ts = tInformationMapper.selectByExample(t);


        List<Map> datas = new ArrayList<Map>();

        if(ApiOperateEnum.REFRESH.getName().equals(page.getHandle())){
            List<Map> top = getTopData(id);
            if(CollectionUtils.isNotEmpty(top)){
                datas.addAll(top);
            }
        }

        datas.addAll(getRenderData(ts));

        p.setPageSize(page.getPageSize());

        p.setItems(datas);
        return p;
    }

    //普通栏目列表数据获取
    private Pager getNavDataPager(NavReqVO page) throws Exception{
        Pager p = new Pager();

        if(page.getPageSize()>ApiConstants.MAX_NUM)
            throw new Exception("pageSize超负荷");


        //基础服务搜索相关
        TInformationCriteria total = new TInformationCriteria();
        TInformationCriteria.Criteria cBase = total.createCriteria();
        //速度会有些慢  上下架
        cBase.andStatusEqualTo(STATUS_PUBLISHED).andIsShowEqualTo(TypeConstants.AppConstants.IF_INFO_SHOW);

        TInformationCriteria total_author = new TInformationCriteria();
        TInformationCriteria.Criteria cAuthor = total_author.createCriteria();
        //速度会有些慢  上下架
        cAuthor.andStatusEqualTo(STATUS_PUBLISHED).andIsShowEqualTo(TypeConstants.AppConstants.IF_INFO_SHOW);

        //搜索名称
        if(StringUtil.isNotBlank(page.getTitle())){

            cBase.andTitleLike("%"+page.getTitle()+"%");
            cAuthor.andAuthorLike("%"+page.getTitle()+"%");
            total.or(cAuthor);
        }

        if(page.getDataId() > -1){
            //搜索数据行为
            page.setHandle(ApiOperateEnum.DOWN.getName());
        }

        //翻页
        total.setLimitStart(0);
        total.setLimitEnd(page.getPageSize());

        informationService.orderByAndSetId(page, total, cBase);

        p.setTotalCount(tInformationMapper.countByExample(total));

        List<TInformation> ts = tInformationMapper.selectByExample(total);
        List<Map> datas = new ArrayList<Map>();

        datas.addAll(getRenderData(ts));

        p.setPageSize(page.getPageSize());

        p.setItems(datas);
        return p;
    }

    //普通栏目置顶数据
    private List<Map> getTopData(int id){
        TInformationCriteria top = new TInformationCriteria();
        TInformationCriteria.Criteria ctop = top.createCriteria();
        top.setOrderByClause("id desc,`info_id` desc");
        top.setLimitStart(0);
        top.setLimitEnd(1);
        ctop.andNavTypeEqualTo(id)
                .andFloorTypeEqualTo(ApiFloorEnum.TOP.getValue())
                .andIsIntroNotEqualTo(TypeConstants.AppConstants.IF_INTRO);

        List<TInformation> ts = tInformationMapper.selectByExample(top);
        return getRenderData(ts);
    }

    //推荐的置顶数据
    private List<Map> getRecommendTopData(){
        TInformationCriteria top = new TInformationCriteria();
        TInformationCriteria.Criteria ctop = top.createCriteria();
        top.setOrderByClause("id desc,`info_id` desc");
        top.setLimitStart(0);
        top.setLimitEnd(1);
        ctop.andFloorTypeEqualTo(ApiFloorEnum.TOP.getValue()).
                andIsIntroEqualTo(TypeConstants.AppConstants.IF_INTRO);

        List<TInformation> ts = tInformationMapper.selectByExample(top);
        return getRenderData(ts);
    }


    /**
     * 专门给列表数据返回拼装数据的方法
     */
    private List<Map> getRenderData(List<TInformation> ts) {
        List<Map> datas = new ArrayList<Map>();
        for(TInformation art:ts){
            Map temp = new HashMap();
            Map dataItem = new HashedMap();
            String imgUrl = art.getCoverUrl();
            String[] imgUrls = imgUrl.split(ApiConstants.IMG_SPLIT);
            //兼容，后期需更迭
            if(ifAliyunImg(art)){
                temp.put("img_url", genAppImg(imgUrls,art.getFloorType(),art.getImgStatus().toString()));
            }else{
                temp.put("img_url", genAppImg(imgUrls,art));
            }
            temp.put("name",art.getTitle());
            temp.put("link",art.getId().toString());
            temp.put("dataId",art.getId().toString());
            temp.put("author",art.getAuthor());
            Date publishTime = DateUtil.getDate(art.getPublishTime(),"yyyy-MM-dd HH:mm:ss");
            temp.put("publishTime", publishTime==null?DateUtil.getSysDate().getTime():publishTime.getTime());
//            temp.put("ocTime", publishTime==null? Math.round(DateUtil.getSysDate().getTime()/1000): Math.round(publishTime.getTime()/1000));
            //图文专区有两种
            if(art.getFloorType().equals(TypeConstants.floorMap.get(TypeConstants.IMAGE_FLOOR))){
                dataItem.put("code",art.getImgStatus().toString());
            }else{
                dataItem.put("code",art.getFloorType());
            }

            dataItem.put("item",temp);
            datas.add(dataItem);
        }
        return datas;
    }



    /**
     * 专门给轮播数据返回拼装数据的方法
     */
    private List<Map> getSliderRenderData(List<TInformation> ts) {
        List<Map> datas = new ArrayList<Map>();
        for(TInformation art:ts){
            Map temp = new HashMap();
            //兼容，后期需更迭
            temp.put("img_url", genAppSliderImg(art));
            temp.put("name",art.getTitle());
            temp.put("link",art.getId().toString());
            temp.put("author",art.getAuthor());
            temp.put("dataId",art.getId().toString());
            Date publishTime = DateUtil.getDate(art.getPublishTime(),"yyyy-MM-dd HH:mm:ss");
            temp.put("publishTime", publishTime==null?DateUtil.getSysDate().getTime():publishTime.getTime());
            datas.add(temp);
        }
        return datas;
    }

    private List<String> genAppImg(String[] imgUrls,TInformation art){

        List<String> urls = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(Arrays.asList(imgUrls))){
            if(imgUrls.length == 1){
                urls.add(art.getCoverUrl1());
            }else if(imgUrls.length == 2){
                urls.add(art.getCoverUrl1());
                urls.add(art.getCoverUrl2());

            }else if(imgUrls.length == 3){
                urls.add(art.getCoverUrl1());
                urls.add(art.getCoverUrl2());
                urls.add(art.getCoverUrl3());

            }
        }

        return urls;
    }

    private List<String> genAppImg(String[] imgUrls,String code,String imgStatus){

        return informationService.genAppImg(imgUrls,code,imgStatus);
    }

    private List<String> genAppSliderImg(TInformation art){
        List<String> urls = new ArrayList<>();
        if(StringUtil.isNotBlank(art.getCoverUrl4())){
            urls.add(art.getCoverUrl4());
        }else{
            String imgUrl = art.getCoverUrl();
            String[] imgUrls = imgUrl.split(ApiConstants.IMG_SPLIT);
            urls = genAppImg(imgUrls,art.getFloorType(),art.getImgStatus().toString());
        }
        return urls;
    }

}
